package com.cn.wanxi.servlet.back.user;

import com.alibaba.fastjson.JSONObject;
import com.cn.wanxi.model.PageModel;
import com.cn.wanxi.model.UserModel;
import com.cn.wanxi.service.IUserService;
import com.cn.wanxi.service.impl.UserServiceImpl;
import com.cn.wanxi.util.DataEncoding;
import com.cn.wanxi.util.JDBCUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet("/back/user/info")
public class UserInfoServlet extends HttpServlet {
    IUserService userService = new UserServiceImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        //用户详情
        String userid = req.getParameter("id");
        int id = 0;
        if (!"".equals(userid))
           id = Integer.parseInt(userid);
        UserModel userModel = userService.getUser(id);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("user",userModel);
        resp.getWriter().print(jsonObject);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DataEncoding.setJsonContentType(resp);
        DataEncoding.setCharacterEncoding(req,resp);
        //用户模糊查询
        String username = req.getParameter("username");
        String start_birth = req.getParameter("startbirth");
        String end_birth = req.getParameter("endbirth");
        String phone = req.getParameter("phone");
        String sex = req.getParameter("sex").trim();
        String pageSize = req.getParameter("page");
        String pageNum = req.getParameter("size");
        String sort = req.getParameter("sort");
        int page = Integer.parseInt(pageSize);
        int size = Integer.parseInt(pageNum);
        Map<String,Object> map = new HashMap<>();
        map.put("username",username);
        map.put("start_birth",start_birth);
        map.put("end_birth",end_birth);
        map.put("phone",phone);
        map.put("sex",sex);
        map.put("page",(page-1)*size);
        map.put("size",size);
        map.put("sort",sort);
        PageModel<UserModel> userList = userService.getUsers(map);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("users",userList);
        resp.getWriter().print(jsonObject);
    }
}
